package com.management.demo.controller.wx;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.management.demo.domain.wx.WxUser;
import com.management.demo.dto.wx.WxUserDTO;
import com.management.demo.properties.WXProperties;
import com.management.demo.service.WxUserService;
import com.management.demo.vo.wx.WxUserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信用户接口")
@RestController
@RequestMapping("wx/user")
public class WXUserController {

    @Autowired
    private WXProperties wxProperties;

    @Autowired
    private WxUserService wxUserService;

    @Operation(summary = "登录")
    @GetMapping("login/{code}")
    public SaResult login(@Parameter(description = "微信用户临时code")
                          @PathVariable String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", wxProperties.getAppId());
        paramMap.put("secret", wxProperties.getAppSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        String openid = JSONUtil.parseObj(result).getStr("openid");
        WxUser wxUser = wxUserService.getOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenid, openid));
        if (wxUser == null) {
            wxUser = new WxUser();
            wxUser.setOpenid(openid);
            wxUserService.save(wxUser);
        }
        return SaResult.ok().setData(wxUser.getId());
    }

    @Operation(summary = "新增/修改用户信息")
    @PostMapping("createOrEdit")
    public SaResult createOrEdit(@RequestBody WxUserDTO wxUserDTO) {
        WxUser wxUser = BeanUtil.copyProperties(wxUserDTO, WxUser.class);
        boolean result = wxUserService.saveOrUpdate(wxUser);
        return SaResult.ok().setData(result);
    }

    @Operation(summary = "根据id获取用户信息")
    @GetMapping("getById/{id}")
    public SaResult getById(@Parameter(description = "用户id")
                            @PathVariable Integer id) {
        WxUser wxUser = wxUserService.getById(id);
        WxUserVO wxUserVO = BeanUtil.copyProperties(wxUser, WxUserVO.class);
        return SaResult.ok().setData(wxUserVO);
    }
}
